//
//  AVFoundationTool.m
//  AVFoundationDemo
//
//  Created by zl on 2019/9/10.
//  Copyright © 2019 LG. All rights reserved.
//

#import "AVFoundationTool.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>

@implementation AVFoundationTool

+ (UIImage *)firstFrameWithVideoURL:(NSURL *)url size:(CGSize)size {
    NSDictionary *opts = @{AVURLAssetPreferPreciseDurationAndTimingKey: @(NO)};
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
    generator.requestedTimeToleranceAfter = kCMTimeZero;
    generator.requestedTimeToleranceBefore = kCMTimeZero;
    generator.appliesPreferredTrackTransform = YES;
    generator.maximumSize = CGSizeMake(size.width, size.height);
    NSError *error = nil;
    CGImageRef img = [generator copyCGImageAtTime:CMTimeMakeWithSeconds(3, 30) actualTime:NULL error:&error];
    if(error) {
        return nil;
    } else {
        UIImage *image = [UIImage imageWithCGImage:img];
        CGImageRelease(img);
        return image;
    }
}

+ (void)sayWithMessage:(NSString *)msg {
    AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc] init];
    AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:msg?msg:@"Hello World!"];
    [synthesizer speakUtterance:utterance];
}
+ (void)getAssetInfo {
    NSURL *assetURL = [[NSBundle mainBundle] URLForResource:@"三度和弦" withExtension:@"mp3"];
    AVAsset *asset = [AVAsset assetWithURL:assetURL];
    NSArray *keys = @[@"tracks"];
    [asset loadValuesAsynchronouslyForKeys:keys completionHandler:^{
        NSError *error = nil;
        AVKeyValueStatus status = [asset statusOfValueForKey:@"tracks" error:&error];
        switch (status) {
            case AVKeyValueStatusLoaded: {
                NSLog(@"Status Loaded!");
                NSLog(@"----- %lld", asset.duration.value);
                NSLog(@"------ %@", asset.lyrics);
                NSString *keySpace = AVMetadataKeySpaceiTunes;
                NSString *artistKey = AVMetadataiTunesMetadataKeyArtist;
                NSString *albumKey = AVMetadataiTunesMetadataKeyAlbum;
                NSArray *artistMetadata = [AVMetadataItem metadataItemsFromArray:asset.commonMetadata withKey:artistKey keySpace:keySpace];
                NSArray *albumMetadata = [AVMetadataItem metadataItemsFromArray:asset.commonMetadata withKey:albumKey keySpace:keySpace];
                AVMetadataItem *artistItem, *albumItem;
                if(artistMetadata.count > 0) {
                    artistItem = artistMetadata[0];
                }
                if(albumMetadata.count > 0) {
                    albumItem = albumMetadata[0];
                }
                for(AVMetadataItem *item in asset.commonMetadata) {
                    NSLog(@"%@, %@",item.key, item.value);
                }
            }
                break;
            case AVKeyValueStatusFailed:
                NSLog(@"Status Failed!");
                break;
            case AVKeyValueStatusLoading:
                NSLog(@"Status Loading!");
                break;
            case AVKeyValueStatusCancelled:
                NSLog(@"Status Cancelled!");
                break;
            case AVKeyValueStatusUnknown:
                NSLog(@"Staus Unknown!");
                break;
            default:
                break;
        }
    }];
    
     NSArray *keys2 = @[@"availableMetadataFormats"];
    [asset loadValuesAsynchronouslyForKeys:keys2 completionHandler:^{
        NSMutableArray *metaData = [NSMutableArray array];
        for(NSString *format in asset.availableMetadataFormats) {
            [metaData addObjectsFromArray:[asset metadataForFormat:format]];
        }
    }];
}
// 获取相册中媒体文件
+ (void)getSystemMediaFile {
   // 列出所有相册智能相册
//    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
//
//    // 列出所有用户创建的相册
//    PHFetchResult *topLevelUserCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
     
    // 获取所有资源的集合，并按资源的创建时间排序
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
     
    // 在资源的集合中获取第一个集合，并获取其中的图片
    PHCachingImageManager *imageManager = [[PHCachingImageManager alloc] init];
    PHAsset *asset = assetsFetchResults[0];
    [imageManager requestImageForAsset:asset
                                        targetSize:PHImageManagerMaximumSize
                                     contentMode:PHImageContentModeDefault
                                            options:nil
                                    resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        
    }];
    
}

@end
